package com.tom.zx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tom.zx.entity.HouseInformation;
import com.tom.zx.entity.User;
import com.tom.zx.service.IHouseInformationService;
import com.tom.zx.service.IUserService;
import com.tom.zx.vo.HouseInformationVo;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Arrays;

/**
 * 房屋信息 前端控制器
 *
 * @author lp
 * @since 2022-04-09
 */
@RestController
@RequestMapping("/zx/houseInformation")
@AllArgsConstructor
public class HouseInformationController {

  private final IHouseInformationService houseInformationService;
  private final IUserService userService;
  /** 分页查询房屋信息 */
  @GetMapping("page")
  public Page<HouseInformation> houseInformationPage(
      Page<HouseInformation> houseInformationPage, HouseInformation houseInformation) {
    return houseInformationService.page(
        houseInformationPage,
        new LambdaQueryWrapper<HouseInformation>()
            .like(HouseInformation::getAddress, houseInformation.getAddress()));
  }

  /** 按照ids 批量删除房屋信息 */
  @DeleteMapping
  public boolean deleteHouseInformationByIds(@RequestBody Long[] ids) {
    return houseInformationService.removeBatchByIds(Arrays.asList(ids));
  }

  /** 更新或保存 当前房屋信息数据 */
  @PostMapping
  public boolean saveOrUpdate(@RequestBody HouseInformationVo houseInformationVo) {
    return houseInformationService.saveOrUpdate(houseInformationVo);
  }

  @PostMapping("user")
  public void saveOrUpdateUser(
      Principal principal, @RequestBody HouseInformationVo houseInformationVo) {
    final String name = principal.getName();
    final User user = userService.loadUserByUserName(name);
    houseInformationVo.setUserId(user.getId());
    houseInformationService.saveOrUpdate(houseInformationVo);
  }

  @GetMapping("page/user")
  public Page<HouseInformation> houseInformationUserPage(
      Principal principal,
      Page<HouseInformation> houseInformationPage,
      HouseInformation houseInformation) {
    final User user = userService.loadUserByUserName(principal.getName());
    return houseInformationService.page(
        houseInformationPage,
        new LambdaQueryWrapper<HouseInformation>()
            .eq(HouseInformation::getUserId, user.getId())
            .like(HouseInformation::getAddress, houseInformation.getAddress()));
  }
}
